package com.webchat.ugc.repository.dao;

import com.webchat.ugc.repository.entity.ChatMessageEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;


@Repository
public interface IChatMessageDAO extends JpaSpecificationExecutor<ChatMessageEntity>, JpaRepository<ChatMessageEntity, Long> {

    @Query(value = "select distinct mess from ChatMessageEntity mess where "
            + "(mess.sender = :sender or mess.receiver = :receiver) and "
            + "(mess.receiver = :sender or mess.sender = :receiver) order by mess.id desc")
    List<ChatMessageEntity> findAllBySenderAndReceiver(String sender, String receiver);

    Page<ChatMessageEntity> findAllByMessageLike(String message, Pageable pageable);


    @Query(value = "select mess from ChatMessageEntity mess " +
                    "where ((mess.sender = :sourceUserId and mess.receiver = :targetUserId) or " +
                    "(mess.sender = :targetUserId and mess.receiver = :sourceUserId)) " +
                    "and mess.sendDate between :startDate and :endDate")
    Page<ChatMessageEntity> findAllBySenderAndReceiverAndSendDateBefore(String sourceUserId,
                                                                        String targetUserId,
                                                                        Date startDate,
                                                                        Date endDate,
                                                                        Pageable pageable
                                                                        );
}